package com.ruoyi.web.controller.eventbus;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class EventBusContext {
    /**
     同步的eventBus
     */
    private static final EventBus EVENT_BUS = new EventBus();
    /**
     ○ asyncEventBus异步执行线程池
     */

    private static ExecutorService asyncEventBusPool = new ThreadPoolExecutor(10, 200,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue(1024), new ThreadFactoryBuilder()
            .setNameFormat("asyncEventBus-pool-%d").build(), new ThreadPoolExecutor.AbortPolicy());
    /**
     ○ 异步的eventBus
     */

    private static final AsyncEventBus ASYNC_EVENT_BUS = new AsyncEventBus(asyncEventBusPool);
    /**
     ○ 注册bean到eventbus
     */
    public  void register(EventListener eventListener) {

        EVENT_BUS.register(eventListener);

        ASYNC_EVENT_BUS.register(eventListener);
    }
    /**
     ○ 同步触发eventbus事件
     */

    public  void fireEvent(Event event) {
        EVENT_BUS.post(event);
    }
    /**
     ○ 异步触发eventbus事件
     */

    public  void fireAsyncEvent(Event event) {
        ASYNC_EVENT_BUS.post(event);
    }


}
